package com.zhongen.auth.support.mini;

import com.zhongen.auth.support.base.OAuth2ResourceOwnerBaseAuthenticationConverter;
import com.zhongen.common.core.constant.SecurityConstants;
import com.zhongen.common.security.util.OAuth2EndpointUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Set;

/**
 * 小程序认证转换器
 */
public class OAuth2ResourceOwnerMiniAuthenticationConverter
		extends OAuth2ResourceOwnerBaseAuthenticationConverter<OAuth2ResourceOwnerMiniAuthenticationToken> {

	@Override
	public boolean support(String grantType) {
		return SecurityConstants.MINI.equals(grantType);
	}

	@Override
	public OAuth2ResourceOwnerMiniAuthenticationToken buildToken(Authentication clientPrincipal,
			Set<String> requestedScopes, Map<String, Object> additionalParameters) {
		return new OAuth2ResourceOwnerMiniAuthenticationToken(new AuthorizationGrantType(SecurityConstants.MINI),
				clientPrincipal, requestedScopes, additionalParameters);
	}

	/**
	 * 校验扩展参数 密码模式密码必须不为空
	 * @param request 参数列表
	 */
	@Override
	public void checkParams(HttpServletRequest request) {
		MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request);
		// PHONE CODE (REQUIRED)
		String phoneCode = parameters.getFirst(SecurityConstants.MINI_PARAMETER_CODE);
		if (!StringUtils.hasText(phoneCode) || parameters.get(SecurityConstants.MINI_PARAMETER_CODE).size() != 1) {
			OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, SecurityConstants.MINI_PARAMETER_CODE,
					OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI);
		}
	}

}
